package good

import (
	"enjoy_wangyashuo/formdata"
	"enjoy_wangyashuo/internal/model/mysql"
	"enjoy_wangyashuo/pkg"
	"errors"
	"fmt"
	"gorm.io/gorm"
)

// 商品表
type Goods struct {
	gorm.Model
	Title       string `gorm:"type:varchar(255);comment:商品标题"`
	Point       int64  `gorm:"type:int(11);comment:商品积分"`
	Description string `gorm:"varchar(255);comment:商品描述"`
	TypesID     int64  `gorm:"type:int;comment:商品类型ID;"`
	Img         string `gorm:"type:json;comment:商品图片链接"`
	IsGoods     int64  `gorm:"type:int(11);default:0;comment:是否特价;"`
}

// 商品详情
func (g *Goods) GoodsDetailById() (detail Goods, err error) {
	return detail, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Where("id = ?", g.ID).First(&detail).Error
	})
}

// 查询多个商品详情
func (g *Goods) GoodsDetailByIds(ids []int64) (list []Goods, err error) {
	return list, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Where("id in ?", ids).Find(&list).Error
	})
}

// 商品搜索
func (g *Goods) SearchGoodsList(page, pageSize int64) (list []formdata.GoodsInfoList, err error) {
	var info []Goods
	return list, mysql.WithMysql(func(db *gorm.DB) error {
		query := db.Model(&Goods{})
		// 动态添加分类 ID 查询条件
		if g.TypesID > 1 {
			fmt.Println(1)
			query = query.Where("types_id = ?", g.TypesID)
		}
		// 动态添加模糊查询条件
		if len(g.Title) > 0 {
			fmt.Println(2, g.Title)
			query = query.Where("title like ?", "%"+g.Title+"%")
		}
		// 执行分页查询
		err = query.Debug().Offset(int((page - 1) * pageSize)).Limit(int(pageSize)).Find(&info).Error

		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("服务器错误")
		}
		//调用封装的商品详情
		list, err = getGoodsInfoList(db, info)
		return nil
	})
}

// 分类id查询商品
func (g *Goods) GoodsInfoByCategoryId() (list []formdata.GoodsInfoList, err error) {
	var lists []Goods
	return list, mysql.WithMysql(func(db *gorm.DB) error {
		// 初始化查询条件
		query := db.Model(&Goods{})
		if g.TypesID != 0 {
			query = db.Where("types_id = ?", g.TypesID)
		}
		err = query.Find(&lists).Error
		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			return err
		}
		//调用封装的商品详情
		list, err = getGoodsInfoList(db, lists)
		return nil
	})
}

// GetGoodsInfoList 根据商品列表获取商品信息列表 封装
func getGoodsInfoList(db *gorm.DB, lists []Goods) ([]formdata.GoodsInfoList, error) {
	// 如果没有商品，直接返回空列表
	if len(lists) == 0 {
		return nil, nil
	}
	var ids []int64
	for _, val := range lists {
		ids = append(ids, int64(val.ID))
	}
	var gp []GoodSku
	err := db.Model(&gp).Where("goods_id in (?)", ids).Order("price desc").Find(&gp).Error
	// 没有找到 SKU 信息时返回空列表
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	infos := make(map[int64]formdata.GoodsInfoList)
	for _, val := range gp {
		infos[val.GoodsID] = formdata.GoodsInfoList{
			ID:       val.GoodsID,
			SkuId:    int64(val.ID),
			Price:    val.Price,
			VipPrice: val.VipPrice,
			Stock:    val.Stock,
		}
	}
	var list []formdata.GoodsInfoList
	for _, val := range lists {
		Images := pkg.GetImages(val.Img) // 解析json格式图片
		if res, ok := infos[int64(val.ID)]; ok {
			list = append(list, formdata.GoodsInfoList{
				ID:          int64(val.ID),
				SkuId:       res.SkuId,
				Title:       val.Title,
				Point:       val.Point,
				Description: val.Description,
				Img:         Images,
				TypesID:     val.TypesID,
				IsGoods:     val.IsGoods,
				Price:       res.Price,
				VipPrice:    res.VipPrice,
				Stock:       res.Stock,
			})
		}
	}
	return list, nil
}
